package com.woniu.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.woniu.dto.OrderAddDTO;
import com.woniu.dto.OrderEditDTO;
import com.woniu.dto.OrderExportDTO;
import com.woniu.dto.OrderSearchDTO;
import com.woniu.entity.Order;
import com.woniu.service.OrderItemService;
import com.woniu.service.OrderService;
import com.woniu.util.ResponseEnum;
import com.woniu.util.ResponseUtil;
import lombok.var;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private OrderService orderService;
    @Resource
    private OrderItemService orderItemService;


    @PostMapping("/search")
    public ResponseUtil findSearchOrders(@RequestBody OrderSearchDTO searchDTO) {
        return orderService.findSearchOrders(searchDTO);
    }
    @PostMapping("/search/return")
    public ResponseUtil findSearchOrdersReturn(@RequestBody OrderSearchDTO searchDTO) {
        return orderService.findSearchOrdersReturn(searchDTO);
    }

    @GetMapping("/detail/{orderId}")
    public ResponseUtil findOrderDetail(@PathVariable String orderId) {
        return orderItemService.findOrderDetail(orderId);
    }

    // 新增：一次返回主单+收货+明细
    @GetMapping("/fullDetail/{orderId}")
    public ResponseUtil getFullOrderDetail(@PathVariable String orderId) {
        return orderService.getFullOrderDetail(orderId);
    }

    @DeleteMapping("/{orderId}")
    public ResponseUtil deleteOrder(@PathVariable String orderId) {
        return orderService.findDeleteById(orderId);
    }

    @GetMapping("/edit/{orderId}")
    public ResponseUtil getOrderForEdit(@PathVariable String orderId) {
        return orderService.getOrderForEdit(orderId);
    }

    @PutMapping("/edit")
    public ResponseUtil editOrder(@RequestBody OrderEditDTO orderEditDTO) {
        return orderService.editOrder(orderEditDTO);
    }

    @PostMapping("/add")
    public ResponseUtil addOrder(@RequestBody OrderAddDTO orderAddDTO) throws InterruptedException {
        return orderService.addOrder(orderAddDTO);
    }

    // OrderController.java
    @GetMapping("/paidUnshipped")
    public ResponseUtil getPaidUnshippedOrders() {
        return orderService.findPaidUnshippedOrders();
    }

    @PostMapping("/approval")
    public ResponseUtil submitApproval(@RequestBody Map<String, String> params) {
        String orderId = params.get("orderId");
        System.out.println(orderId);
        if (StringUtils.isBlank(orderId)) {
            return ResponseUtil.get(ResponseEnum.FAIL, "订单ID不能为空");
        }
        return orderService.submitApproval(orderId);
    }

    // 订单导出excel
    @GetMapping("/export")
    public void exportOrders(HttpServletResponse response) throws Exception {
        // 设置响应头（关键：不返回 JSON，而是文件流）
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        String fileName = URLEncoder.encode("订单数据导出", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        try (var writer = EasyExcel.write(response.getOutputStream(), OrderExportDTO.class).build()) {
            WriteSheet sheet = EasyExcel.writerSheet("订单列表").build();

            int pageIndex = 0;
            long total = orderService.countTotalOrders();
            int pageSize = 1000;

            do {
                List<OrderExportDTO> data = orderService.findExportOrders(pageIndex);
                if (data.isEmpty()) break;

                writer.write(data, sheet);
                pageIndex++;
            } while (pageIndex * pageSize < total);
        }
    }

    // 退货审核
    @PutMapping("/return")
    public ResponseUtil editOrderReturn(@RequestBody Order order) {
        return orderService.editOrderReturn(order);
    }

}
